#include "execsql.h"

#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlTableModel>

#include <QDebug>

void ExecSQL::searchAllUserInfos()
{
    QString queryString = QString("select * from usr_info");
    qDebug() << queryString;

    updateUserInfoList(queryString);
}

void ExecSQL::searchUserInfoForID(const QString &value)
{
    QString queryString = QString("select * from usr_info where id = '%1'").arg(value);
    qDebug() << queryString;

    updateUserInfoList(queryString);
}

void ExecSQL::searchUserInfoForRole(const QString &value)
{
    QString queryString = QString("select * from usr_info where role = '%1'").arg(value);
    qDebug() << queryString;

    updateUserInfoList(queryString);
}

void ExecSQL::searchUserInfoForDate(const QString &value)
{
    QString queryString = QString("select * from usr_info where date = '%1'").arg(value);
    qDebug() << queryString;

    updateUserInfoList(queryString);
}

void ExecSQL::updateUserInfoList(const QString &sql)
{
    QSqlQuery query;
    GlobalVars::g_usrInfoList.clear();
    GlobalVars::g_usrInfoMap.clear();
    if(query.exec(sql))
    {
         int id_idx = query.record().indexOf("id");
         int name_idx = query.record().indexOf("name");
         int pswd_idx = query.record().indexOf("pswd");
         int role_idx = query.record().indexOf("role");

         while(query.next())
         {
            QString id = query.value(id_idx).toString();
            QString name = query.value(name_idx).toString();
            QString pswd = query.value(pswd_idx).toString();
            QString role = query.value(role_idx).toString();

            UsrInfo info(id, name, pswd, role);
            GlobalVars::g_usrInfoList.append(info);
         }

         for(UsrInfoList::iterator it = GlobalVars::g_usrInfoList.begin();
             it != GlobalVars::g_usrInfoList.end(); it++)
         {
            GlobalVars::g_usrInfoMap.insert(it->getID(), it);
         }
    }
}
